package cn.wit.summit.chwan.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.core.ImagePipeline;

import java.io.File;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.dto.ApkVersionbean;
import cn.wit.summit.chwan.models.dto.CfgBean;
import cn.wit.summit.chwan.models.dto.CfgMain;
import cn.wit.summit.chwan.models.dto.VersionDto;
import cn.wit.summit.chwan.models.response.ChangeIconResponse;
import cn.wit.summit.chwan.models.response.CodeloginRespone;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.ui.receiver.BroadcastAction;
import cn.wit.summit.chwan.ui.service.AppUpdataVersionService;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.FileUtil;
import cn.wit.summit.chwan.utils.JsonMapper;
import cn.wit.summit.chwan.utils.NameLengthFilter;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PermissionManagerUtil;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.SystemInfoUtils;
import cn.wit.summit.chwan.utils.TCUploadHelper;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.utils.UtilsMy;
import cn.wit.summit.chwan.widgets.LodingDialog;
import cn.wit.summit.chwan.widgets.VersionUpdataDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class SettingActivity extends MyActivity implements TCUploadHelper.OnUploadListener {

    @Bind(R.id.rl_ChangePwd)
    RelativeLayout rl_changePwd;
    @Bind(R.id.rl_ChangeName)
    RelativeLayout rl_changeName;
    @Bind(R.id.tv_name)
    TextView tv_name;
    @Bind(R.id.btn_login_out)
    Button btn_login_out;
    @Bind(R.id.rl_ChangeIcon)
    RelativeLayout rl_icon;
    @Bind(R.id.icon)
    SimpleDraweeView iv_icon;
    @Bind(R.id.root)
    FrameLayout root;
    @Bind(R.id.checkVersionTv)
    TextView checkVersionTv;

    InputFilter[] filter;
    PopupWindow mPopWindow;
    private static final int CAPTURE_IMAGE_CAMERA = 100;
    private static final int IMAGE_STORE = 200;
    private static final int CROP_CHOOSE = 10;
    private Uri fileUri, cropUri;
    private Dialog mPicChsDialog;
    private boolean mPermission;
    private boolean mUploading = false;
    private TCUploadHelper mUploadHelper;

    private RetrofitManager retrofitManager;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;
    private Retrofit retrofit;
    private ApiUtil api;

    private String[] version;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        setBarTitleTx(getString(R.string.setting));

        version = SystemInfoUtils.getInstance(SettingActivity.this).getVersionNameArray();

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

//        sps = MyApplication.getMyApplication().getShareFer();
        tv_name.setText(MyApplication.accountBean.getNickname());
        iv_icon.setImageURI(MyApplication.accountBean.getAvatar());

        if (version!=null && version.length>1) {
            checkVersionTv.setText("v"+version[1]);
        }
    }


    private boolean matchStringLength(String s, int min, int max) {
        int sLength = getStringLength(s);
        return sLength >= min && sLength <= max;
    }

    private int getStringLength(String s) {
        if (StringUtils.isEmpty(s)) return 0;

        return s.length() + getChineseCount(s);
    }

    private int getChineseCount(String str) {
        int count = 0;
        String regEx = "[\\u4e00-\\u9fa5]"; // unicode编码，判断是否为汉字
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        while (m.find()) {
            for (int i = 0; i <= m.groupCount(); i++) {
                count = count + 1;
            }
        }
        return count;
    }

    boolean isc = false;


    private void showPopupWindow() {
        View contentView = LayoutInflater.from(SettingActivity.this).inflate(R.layout.appointment_pay_popwindow_page, null);
        mPopWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        NameLengthFilter filters = new NameLengthFilter(16, SettingActivity.this);
        filter = new InputFilter[]{filters};
        final EditText edit = contentView.findViewById(R.id.edit);
        edit.setFilters(filter);
        final LinearLayout ll_root = contentView.findViewById(R.id.toot);
        final TextView tv_que = contentView.findViewById(R.id.tv_confirm);
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        tv_que.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
                boolean name = matchStringLength(edit.getText().toString(), 4, 16);
                if (name) {
                    setNetChangeName(edit.getText().toString().trim());
                } else {
                    Toast.makeText(SettingActivity.this, "昵称格式有误，输入4至16位字母或2至8汉字", Toast.LENGTH_SHORT).show();
                }

            }
        });
        edit.setFocusable(true);
        mPopWindow.setFocusable(true);
        edit.setFocusableInTouchMode(true);
        edit.setFocusable(true);
        edit.requestFocus();
        InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        m.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
        final View decorView = getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                int displayHight = rect.bottom - rect.top;
                int hight = decorView.getHeight();
                if (displayHight > hight / 3 * 2) {
                    if (isc == true) {
                        mPopWindow.dismiss();
                        isc = false;
                    }
                } else {
                    isc = true;
                }
            }
        });
        //显示PopupWindow
        View rootview = LayoutInflater.from(SettingActivity.this).inflate(R.layout.activity_setting, null);
        showPopmenu(rootview);
    }

    /**
     * 上传网名
     */
    private void setNetChangeName(final String na) {
        if (NetWorkUtils.isNetworkConnected(SettingActivity.this)) {
            if (StringUtils.isNotEmpty(na)) {
                int uid = MyApplication.accountBean.getUid();
                String token = MyApplication.accountBean.getToken();
                if (token == null) {
                    showToast("Token为空");
                    return;
                }
                apiLogin.modifyNick(na, uid + "", token).enqueue(new MyCallback<ResponseBase<CodeloginRespone>>() {
                    @Override
                    public void onSuccess(ResponseBase<CodeloginRespone> model) {
                        showToast("修改成功");
                        ToastUtils.getInstance(SettingActivity.this).showToastSystem("修改成功");
                        AccountBean bean = MyApplication.accountBean;
                        bean.setNickname(na);
                        bean.setDefaultNickname(1);
                        AccountUtil.getInstance().saveAccountData(bean);
                        tv_name.setText(bean.getNickname());
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        showToast(msg);
                    }
                });

            } else {
                ToastUtils.getInstance(SettingActivity.this).showToastSystem("昵称不能为空");
            }
        } else {
            ToastUtils.getInstance(SettingActivity.this).showToastSystem("网络连接失败，再试试吧~");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void showPopmenu(View rootview) {
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        // 显示窗口位置
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1.0f;
        getWindow().setAttributes(lp);
    }

    @OnClick({R.id.rl_ChangePwd, R.id.rl_ChangeName, R.id.btn_login_out, R.id.rl_ChangeIcon})
    public void OnClickView(View view) {
        switch (view.getId()) {
            case R.id.rl_ChangePwd:
                startActivity(new Intent(SettingActivity.this, ChangePwdActivity.class));
                break;
            case R.id.rl_ChangeName:
                ChangName();
                break;
            case R.id.btn_login_out:
                AccountUtil.getInstance().accountLoginOut(mAty);
                finish();
                //退出登录要做什么操作
                break;
            case R.id.rl_ChangeIcon:
                //修改头像
                ChangIcon();
//                startActivity(new Intent(SettingActivity.this, MainLoginActivity.class));
                break;
        }
    }

    private void ChangName() {
        showPopupWindow();
    }

    /**
     * 修改头像
     */
    private void ChangIcon() {
        mUploadHelper = new TCUploadHelper(SettingActivity.this, this);
        dialog = new LodingDialog(SettingActivity.this);
        mPicChsDialog = new Dialog(SettingActivity.this, R.style.floate_dialog);
        mPicChsDialog.setContentView(R.layout.dialog_pic_choose);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Window dlgwin = mPicChsDialog.getWindow();
        WindowManager.LayoutParams lp = dlgwin.getAttributes();
        dlgwin.setGravity(Gravity.BOTTOM);
        lp.width = display.getWidth(); //设置宽度
        mPicChsDialog.getWindow().setAttributes(lp);
        TextView camera = (TextView) mPicChsDialog.findViewById(R.id.chos_camera);
        TextView picLib = (TextView) mPicChsDialog.findViewById(R.id.pic_lib);
        TextView cancel = (TextView) mPicChsDialog.findViewById(R.id.btn_cancel);
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPicFrom(CAPTURE_IMAGE_CAMERA);
                mPicChsDialog.dismiss();
            }
        });

        picLib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPicFrom(IMAGE_STORE);
                mPicChsDialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPicChsDialog.dismiss();
            }
        });
        mPicChsDialog.show();


    }

    int index;

    /**
     * 获取图片资源
     *
     * @param type 类型（本地IMAGE_STORE/拍照CAPTURE_IMAGE_CAMERA）
     */
    private void getPicFrom(int type) {
        String path = Environment.getExternalStorageDirectory() + "/chwdownload/imageupload";
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
        File[] fs = f.listFiles();
        if (fs != null) {
            for (File fi : fs) {
                if (fi.exists() && fi.isFile() && fi.getName().endsWith(".jpg")) {
                    UtilsMy.delete(fi);
                }
            }
        }
        switch (type) {
            case CAPTURE_IMAGE_CAMERA:
                index = 1;
                if (Build.VERSION.SDK_INT >= 23) {
                    int permission = ContextCompat.checkSelfPermission(SettingActivity.this, Manifest.permission.CAMERA);
                    if (permission != PackageManager.PERMISSION_GRANTED) {
                        checkPublishPermission(index);
                        if (granted == false) {
                            return;
                        }
                    }
                }
                Intent intent_photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent_photo.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    fileUri = FileProvider.getUriForFile(SettingActivity.this, "cn.wit.summit.chwan.fileprovider", getfileAbsupath(""));
                } else {
                    fileUri = createCoverUri("");
                }
                Log.e("TAG", "FF:" + fileUri);
                intent_photo.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                intent_photo.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                startActivityForResult(intent_photo, CAPTURE_IMAGE_CAMERA);
                Log.e("TAG", "2");

                break;
            case IMAGE_STORE:
                index = 2;
                if (Build.VERSION.SDK_INT >= 23) {
                    if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        checkPublishPermission(index);
                        if (granted2 == false) {
                            return;
                        }
                    }
                }

                fileUri = createCoverUri("_select");
//                Intent intent_album = new Intent("android.intent.action.GET_CONTENT");
//                intent_album.setType("image/*");
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, IMAGE_STORE);
                break;

        }
    }

    LodingDialog dialog = null;
    private boolean granted;
    private boolean granted2;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults.length > 0) {
            if (index == 1) {
                granted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (granted == false)
                    ToastUtils.getInstance(SettingActivity.this).showToastSystem("权限不足");
            } else if (index == 2) {
                granted2 = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (granted2 == false)
                    ToastUtils.getInstance(SettingActivity.this).showToastSystem("权限不足");
            }

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAPTURE_IMAGE_CAMERA:
                    startPhotoZoom(fileUri);
                    break;
                case IMAGE_STORE:
                    String path = FileUtil.getPath(this, data.getData());
                    if (null != path) {
                        File file = new File(path);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            startPhotoZoom(FileProvider.getUriForFile(SettingActivity.this, "cn.wit.summit.chwan.fileprovider", file));
                        } else {
                            startPhotoZoom(Uri.fromFile(file));
                        }

                    }
                    break;
                case CROP_CHOOSE:
                    mUploading = true;
//                    tvPicTip.setVisibility(View.GONE);
//                    liverIcon.setImageBitmap(null);
                    ImagePipeline imagePipeline = Fresco.getImagePipeline();
                    imagePipeline.evictFromMemoryCache(cropUri);
                    imagePipeline.evictFromDiskCache(cropUri);
                    imagePipeline.evictFromCache(cropUri);
                    //上传头像
                    if (NetWorkUtils.isNetworkConnected(SettingActivity.this)) {
                        File file = new File(cropUri.getPath());

                        MultipartBody.Builder builder = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM);//表单类型
                        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        builder.addFormDataPart("files", file.getName(), imageBody);//imgfile 后台接收图片流的参数名

                        MultipartBody.Part part = builder.build().part(0);
                        String token = MyApplication.accountBean.getToken();
                        if (token == null) {
                            showToast("Token为空");
                            return;
                        }
                        RequestBody tokenBody = RequestBody.create(MediaType.parse("form-data"), token);
                        apiLogin.getChangeIcon(part, MyApplication.accountBean.getUid(), tokenBody)
                                .enqueue(new Callback<ChangeIconResponse>() {
                                    @Override
                                    public void onResponse(Call<ChangeIconResponse> call, Response<ChangeIconResponse> response) {
                                        if (call.isCanceled()) return;
                                        if (dialog != null)
                                            dialog.dismiss();
                                        ChangeIconResponse model = response.body();
                                        if (model.getCode() == 600) {
                                            AccountBean bean1 = MyApplication.accountBean;
                                            bean1.setAvatar(model.getData_info().getAvatarImg());
                                            AccountUtil.getInstance().saveAccountData(bean1);
                                            iv_icon.setImageURI(bean1.getAvatar());
                                            Toast.makeText(SettingActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(SettingActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<ChangeIconResponse> call, Throwable t) {
                                        if (call.isCanceled()) return;
                                        if (dialog != null)
                                            dialog.dismiss();
                                        Toast.makeText(SettingActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                                    }
                                });

//                        OkHttpUtil.getDefault(this).doUploadFileAsync(BuildRequestUtils.getInstance(this).getChangeIcon(cropUri.getPath(),
//                                MyApplication.accountBean.getUid() + "", MyApplication.accountBean.getToken()), new ProgressCallback() {
//                            @Override
//                            public void onResponseMain(String filePath, HttpInfo info) {
//                                super.onResponseMain(filePath, info);
//                                dialog.dismiss();
//                                //解析
//                                LogUtils.e(">>>>>>:" + info.getRetDetail());
//                                Gson gson = new Gson();
//                                ChangeIconResponse bean = gson.fromJson(info.getRetDetail(), ChangeIconResponse.class);
//                                if (bean.getCode() == 600) {
//                                    AccountBean bean1 = MyApplication.accountBean;
//                                    bean1.setAvatar(bean.getData_info().getAvatarImg());
//                                    AccountUtil.getInstance().saveAccountData(bean1);
//                                    iv_icon.setImageURI(bean1.getAvatar());
//                                    Toast.makeText(SettingActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
//                                } else if (bean.getCode() == -1) {
//                                    Toast.makeText(SettingActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
//                                }
//
//                            }
//
//                            @Override
//                            public void onProgressMain(int percent, long bytesWritten, long contentLength, boolean done) {
//                                super.onProgressMain(percent, bytesWritten, contentLength, done);
//                                LogUtils.e(">>>>>>percent:" + percent + ",done:" + done);
//                            }
//                        });

                        dialog.showdialog();
                        dialog.setText("正在上传");
                        dialog.setCancelable(false);
                        break;
                    } else {
                        ToastUtils.getInstance(SettingActivity.this).showToastSystem("网络连接失败，再试试吧~");
                    }
            }
        }
    }

    public static final int WRITE_PERMISSION_REQ_CODE = 2;

    private void checkPublishPermission(int type) {


        switch (type) {
            case 1:
                //拍照
                int permission = ContextCompat.checkSelfPermission(SettingActivity.this, Manifest.permission.CAMERA);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    //去申请
                    if (shouldRequest(1)) return;
                    ActivityCompat.requestPermissions(SettingActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                }
                break;
            case 2:
                //从相册选择
                if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    if (shouldRequest(2)) return;
                    ActivityCompat.requestPermissions(SettingActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                }

                break;

        }


    }

    private boolean shouldRequest(int o) {
        if (o == 1) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                //显示一个对话框，给用户解释
                explainDialog(o);
                return true;
            }
        } else if (o == 2) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                //显示一个对话框，给用户解释
                explainDialog(o);
                return true;
            }
        }

        return false;
    }

    private void explainDialog(int i) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if (i == 1) {
            ActivityCompat.requestPermissions(SettingActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
        } else if (i == 2) {
            ActivityCompat.requestPermissions(SettingActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        }

    }

    private Uri createCoverUri(String type) {
        String filename = AccountUtil.getInstance().getUid() + type + System.currentTimeMillis() + ".jpg";
//        String filename = TCUserInfoMgr.getInstance().getUserId() + type + System.currentTimeMillis() + ".jpg";
        String path = Environment.getExternalStorageDirectory() + "/chwdownload/imageupload";
        Log.e("TAG", "拍照1" + path.toString());
//        File f = new File(path);
//        if (!f.exists()){
//            f.mkdirs();
//        }

//        File[] fs = f.listFiles();
//
//        for (File fi : fs) {
//            if (fi.exists() && fi.isFile() && fi.getName().endsWith(".jpg")) {
//                UtilsMy.delete(fi);
//            }
//        }
        File outputImage = new File(path, filename);
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
//            return null;
//        }
        try {
            File pathFile = new File(path);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            if (outputImage.exists()) {
                outputImage.delete();
            }
//            outputImage.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(SettingActivity.this, "生成封面失败", Toast.LENGTH_SHORT).show();
        }

        return Uri.fromFile(outputImage);
    }

    private File getfileAbsupath(String type) {
        String filename = AccountUtil.getInstance().getUid() + type + System.currentTimeMillis() + ".jpg";
//        String filename = TCUserInfoMgr.getInstance().getUserId() + type + System.currentTimeMillis() + ".jpg";
        String path = Environment.getExternalStorageDirectory() + "/chwdownload/imageupload";
        Log.e("TAG", "拍照1" + path.toString());
//        File f = new File(path);
//        if (!f.exists()){
//            f.mkdirs();
//        }

//        File[] fs = f.listFiles();
//
//        for (File fi : fs) {
//            if (fi.exists() && fi.isFile() && fi.getName().endsWith(".jpg")) {
//                UtilsMy.delete(fi);
//            }
//        }
        File outputImage = new File(path, filename);
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_PERMISSION_REQ_CODE);
//            return null;
//        }
        try {
            File pathFile = new File(path);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            if (outputImage.exists()) {
                outputImage.delete();
            }
//            outputImage.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(SettingActivity.this, "生成封面失败", Toast.LENGTH_SHORT).show();
        }

        return outputImage;
    }

    public void startPhotoZoom(Uri uri) {
        cropUri = createCoverUri("_crop");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 340);
        intent.putExtra("aspectY", 290);
        intent.putExtra("outputX", 340);
        intent.putExtra("outputY", 290);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);//去黑边
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }

        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, CROP_CHOOSE);
    }

    @Override
    public void onUploadResult(int code, String url) {
        Log.e("uploadData", "  onUploadResult " + url);
        dialog.dismiss();
        dialog.setText("请稍候...");
        if (0 == code) {
            Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "上传失败，错误码 " + code, Toast.LENGTH_SHORT).show();
        }
        mUploading = false;

    }

    @OnClick(R.id.checkVersionRl)
    public void onViewClicked() {
        showLoading("");
        checkVersion();
    }

    private void checkVersion() {
        api.getPlug(0).enqueue(new MyCallback<ResponseBase<CfgMain>>() {
            @Override
            public void onSuccess(ResponseBase<CfgMain> model) {
                cancelLoading();
                CfgMain data = model.getData_info();
                if (data != null) {
                    try {
                        CfgBean cfgBean = data.getCfg();
                        String cfgS = JsonMapper.getInstance().toJson(cfgBean);
                        PreferenceUtil.saveNergyUrlPreference(getApplicationContext(), cfgS);
                        MyApplication.cfgPlug = cfgBean;
                        MyApplication.arrayCommentExplain = data.getCfg().getArray_comment_explain();
                        MyApplication.arrayUploadExplain = data.getCfg().getArray_upload_explain();
                        ApkVersionbean apkVersionbeanApp = data.getApp();

                        String nVersion = apkVersionbeanApp.getVer();

                        // 新版本大版本号
                        int nCode = Integer.parseInt(nVersion.split("_")[0]);
                        // 最低版本要求
                        String compatible = apkVersionbeanApp.getVer_compatible();
                        int cCode = Integer.parseInt(compatible.split("_")[0]);
                        if (Integer.parseInt(version[0]) <= nCode) {
                            VersionDto versionDto = new VersionDto();
                            versionDto.setSize(apkVersionbeanApp.getSize() + "M");
                            versionDto.setVersionName("v " + nVersion.split("_")[1]);
                            versionDto.setAndroidUrl(apkVersionbeanApp.getDown_url());
                            versionDto.setVersionNo(Integer.parseInt(nVersion.split("_")[0]));
                            versionDto.setInfo(apkVersionbeanApp.getVer_info());
                            versionDto.setHead_pic(apkVersionbeanApp.getHead_pic());
                            versionDto.setTow_tpl_back_ground_pic(apkVersionbeanApp.getTow_tpl_back_ground_pic());
                            versionDto.setTpl_type(apkVersionbeanApp.getTpl_type());
                            if (Integer.parseInt(version[0]) < nCode) {// 小于大版本号,再判断是否小要强制升级
                                // 判断是否要强制升级
                                if (Float.parseFloat(version[0]) < cCode) {
                                    updataAppVersion(versionDto, true);
                                } else {
                                    updataAppVersion(versionDto, false);
                                }
                            } else {
                                showToast("当前已经是最新版本！", 3000);
                            }
                        } else {
                            showToast("当前已经是最新版本！", 3000);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                cancelLoading();
                showToast(msg);
            }
        });
    }

    private void updataAppVersion(final VersionDto versionDto, final boolean isMust) {
        final VersionUpdataDialog dialog = new VersionUpdataDialog(mContext);
        dialog.show();
        dialog.setTitle(getResources().getString(R.string.updata_dialog_title_str));
        dialog.setVersion(versionDto.getVersionName());
        dialog.setSize(versionDto.getSize());
        dialog.setMsg(versionDto.getInfo());
        if (isMust)
            dialog.setMustUpdate();
        dialog.setCancleBtn(getResources().getString(R.string.updata_dialog_ok_str), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean hasStoragePermiss = PermissionManagerUtil.hasStoragePermission(mContext);
                boolean haveInstallPermission = false;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    //先获取是否有安装未知来源应用的权限
                    haveInstallPermission = getPackageManager().canRequestPackageInstalls();
                    haveInstallPermission = true;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (EasyPermissions.hasPermissions(mContext, Manifest.permission.REQUEST_INSTALL_PACKAGES)) {
                        haveInstallPermission = true;
                    }
                } else {
                    haveInstallPermission = true;
                }
                if (hasStoragePermiss && haveInstallPermission) {//有内存卡权限
                    initPath();
                    Intent intent = new Intent(mContext, AppUpdataVersionService.class);
                    intent.putExtra("data", versionDto);
                    startService(intent);
                    showToast("正在下载更新！");
                    if (!isMust)
                        dialog.dismiss();
                } else {//没有内存卡权限
                    if (!hasStoragePermiss) {
                        Intent intent = new Intent(BroadcastAction.ACTION_CHECKANDREQUEST_PERMISS);
                        intent.putExtra("permisson", PermissionManagerUtil.PERM_STORAGE);
                        sendBroadcast(intent);
                    }
                    if (!haveInstallPermission) {
                        Intent intent = new Intent(BroadcastAction.ACTION_INSTALL_APK);
                        intent.putExtra("permisson", PermissionManagerUtil.PERM_INSTALL);
                        sendBroadcast(intent);
                    }
                }
            }
        });
        if (!isMust) {
            dialog.setBtn(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }
    }
}
